package cz.muni.fi.pa165.dao.impl;

import cz.muni.fi.pa165.dao.EmployeeDAO;
import cz.muni.fi.pa165.entity.Employee;
import cz.muni.fi.pa165.shiro.ShiroSecured;
import java.util.Calendar;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.apache.shiro.authz.annotation.RequiresRoles;

/**
 * @author <a href="mailto:vramik at redhat.com">Vlastislav Ramik</a>
 */
@Stateless
@ShiroSecured
@RequiresRoles("Manager")
public class EmployeeDAOImpl implements EmployeeDAO {
    
    @PersistenceContext(unitName = "pa165")
    private EntityManager em;

    @Override
    public void createEmployee(Employee employee) {
        checkEmployeeAttributes(employee);
        if (employee.getId() != null) {
            throw new IllegalArgumentException("Employee's id has to be null but it's already set");
        }
        em.persist(employee);
    }

    @Override
    public void removeEmployee(Employee employee) {
        if (employee == null) {
            throw new IllegalArgumentException("Employee is null.");
        }
        if (employee.getId() == null) {
            throw new IllegalArgumentException("Employee's id is null.");
        }
        em.remove(em.merge(employee));
    }

    @Override
    public void updateEmployee(Employee employee) {
        checkEmployeeAttributes(employee);
        if (employee.getId() == null) {
            throw new IllegalArgumentException("Employee's id is null.");
        }
        em.merge(employee);
    }

    @Override
    public List<Employee> getAllEmployees() {
        return em.createQuery("select e from Employee e ORDER BY e.name ASC").getResultList();
    }

    @Override
    public Employee getEmployeeById(Long id) {
        return em.find(Employee.class, id);
    }

    private void checkEmployeeAttributes(Employee employee) {
        if (employee == null) {
            throw new IllegalArgumentException("Employee is null");
        }
        if (employee.getName() == null || employee.getName().isEmpty()) {
            throw new IllegalArgumentException("Employee's name is null or empty.");
        }
        if (employee.getBirthDate() == null) {
            throw new IllegalArgumentException("Emlpoyee's birth date is null.");
        }
        Calendar lowLimit = Calendar.getInstance();
        lowLimit.add(Calendar.YEAR, -15);
        
        if (employee.getBirthDate().after(lowLimit.getTime())) {
            throw new IllegalArgumentException("Employee is younger than 15.");
        }
        
        Calendar highLimit = Calendar.getInstance();
        highLimit.add(Calendar.YEAR, -99);
        
        if (employee.getBirthDate().before(highLimit.getTime())) {
            throw new IllegalArgumentException("Employee is older than 99.");
        }
    }

}
